<template>
  <!-- form表单 -->
  <el-form
    :model="formData"
    :rules="rules"
    ref="formData"
    label-width="120px"
    class="demo-formData"
    size="mini"
  >
    <!-- 学科 -->
    <el-form-item label="学科:" prop="subjectID">
      <el-select
        v-model="formData.subjectID"
        placeholder="请选择"
        @focus="changeSubject(formData.subjectID)"
      >
        <el-option
          v-for="item in subjectList"
          :key="item.id"
          :label="item.subjectName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <!-- 目录 -->
    <el-form-item label="目录:" prop="catalogID">
      <el-select v-model="formData.catalogID" placeholder="请选择">
        <el-option
          v-for="item in directorysList"
          :key="item.id"
          :label="item.directoryName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <!-- 企业 -->
    <el-form-item label="企业:" prop="enterpriseID">
      <el-select v-model="formData.enterpriseID" placeholder="请选择">
        <el-option
          v-for="item in enterpriseList"
          :key="item.id"
          :label="item.shortName"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>
    <!-- 城市 -->
    <el-form-item
      label="城市:"
      prop="province"
      class="city"
      @change.native="getArea"
    >
      <el-select v-model="formData.province" placeholder="请选择">
        <el-option
          v-for="(item, i) in provincesList"
          :key="i"
          :label="item.city"
          :value="item.city"
        ></el-option>
      </el-select>
      <el-select v-model="formData.city" placeholder="请选择">
        <el-option
          v-for="(item, i) in cityList"
          :key="i"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
    </el-form-item>
    <!-- 方向 -->
    <el-form-item label="方向:" prop="direction">
      <el-select v-model="formData.direction" placeholder="请选择">
        <el-option
          v-for="(item, i) in directionList"
          :key="i"
          :label="item"
          :value="item"
        ></el-option>
      </el-select>
    </el-form-item>
    <!-- 题型 -->
    <el-form-item label="题型:" prop="questionType">
      <el-radio-group v-model="formData.questionType">
        <el-radio label="1">单选</el-radio>
        <el-radio label="2">多选</el-radio>
        <el-radio label="3">简答</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 难度 -->
    <el-form-item label="难度:" prop="difficulty">
      <el-radio-group v-model="formData.difficulty">
        <el-radio label="1">简单</el-radio>
        <el-radio label="2">一般</el-radio>
        <el-radio label="3">困难</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 题干 -->
    <!-- 富文本模块 -->
    <el-form-item label="题干:" prop="question">
      <quill-editor
        :options="editorOption"
        v-model="formData.question"
      ></quill-editor>
    </el-form-item>

    <!-- 选项 -->
    <!-- 单选 -->
    <el-form-item label="选项:" v-if="formData.questionType === '1'">
      <el-radio-group
        v-for="(item, i) in formData.options"
        :key="i"
        class="option_item"
        v-model="item.isRight"
        @change="changeIsRight(i)"
        @click="addImg(i)"
      >
        <el-radio v-model="item.code" :label="1">{{ item.code }}</el-radio>
        <el-input v-model="item.title" placeholder="" />
        <div class="uploadImg">
          <input
            @change="preview"
            ref="uploadInput"
            type="file"
            accept="image/*"
            hidden
          />
          <span @click="chooseImg(i)">上传图片</span>
          <i class="el-icon-circle-close"></i>
        </div>
      </el-radio-group>
      <!-- 单选禁用button -->
      <el-button
        disabled
        type="danger"
        style="background-color: #fab6b6; border-color: #fab6b6"
        >+增加选项与答案</el-button
      >
    </el-form-item>
    <!-- 多选 -->
    <el-form-item label="选项:" v-if="formData.questionType === '2'">
      <el-checkbox-group
        v-for="(item, j) in formData.options"
        :key="j"
        v-model="item.isRight"
        :true-label="item.isRight"
        :min="3"
        :max="5"
        class="option_item"
        @click="changeImg(j)"
      >
        <el-checkbox v-model="item.code" :true-label="1">{{
          item.code
        }}</el-checkbox>
        <el-input v-model="item.title" placeholder="" />
        <div class="uploadImg">
          <input
            @change="preview"
            ref="uploadInput"
            type="file"
            accept="image/*"
            hidden
          />
          <span @click="chooseImg(j)">上传图片</span>
          <i class="el-icon-circle-close"></i>
        </div>
      </el-checkbox-group>
      <!-- 多选不禁用button -->
      <el-button
        type="danger"
        style="background-color: #fab6b6; border-color: #fab6b6"
        @click="addCheckboxList"
        >+增加选项与答案</el-button
      >
    </el-form-item>

    <!-- 解析视频 -->
    <el-form-item label="解析视频:">
      <el-input v-model="formData.videoURL" placeholder=""></el-input>
    </el-form-item>
    <!-- 答案解析 -->
    <el-form-item label="答案解析:" prop="answer">
      <quill-editor
        :options="editorOption"
        v-model="formData.answer"
      ></quill-editor>
    </el-form-item>
    <!-- 题目备注 -->
    <el-form-item label="题目备注:">
      <el-input type="textarea" v-model="formData.remarks"></el-input>
    </el-form-item>
    <!-- 试题标签 -->
    <el-form-item label="试题标签:">
      <el-select v-model="formData.tags" multiple placeholder="请选择">
        <el-option
          v-for="item in tagsLists"
          :key="item.id"
          :label="item.tagName"
          :value="item.tagName"
        ></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button
        :type="formData.id ? 'success' : 'primary'"
        @click="submitForm"
        >{{ formData.id ? '确认修改' : '确认提交' }}</el-button
      >
    </el-form-item>
  </el-form>
</template>
<script>
// 学科信息
import { list as subjectList } from '@/api/hmmm/subjects.js'
// 目录下拉框
import { list as directorysApi } from '@/api/hmmm/directorys.js'
// 试题标签
import { list as tagsList } from '@/api/hmmm/tags.js'
// 企业信息
import { list } from '@/api/hmmm/companys.js'
// 方向
import { direction } from '@/api/hmmm/constants.js'
// 地区
import { datas } from '@/api/hmmm/citys.js'

// 添加, 详情, 修改
import { add, update } from '@/api/hmmm/questions.js'
// 富文本框引入
import { quillEditor } from 'vue-quill-editor'
// 富文本框样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  components: {
    // 注册富文本编辑器组件
    quillEditor
  },
  data () {
    return {
      // 富文本修改
      editorOption: {
        // 工具菜单栏配置
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            ['blockquote'], // 引用
            ['code-block', 'image', 'link'] // 代码块、图片、链接
          ]
        }
      },
      params: {
        page: 1,
        pagesize: 50
      },
      // 学科名称：
      subjectList: [],
      // 目录
      directorysList: [],
      // 企业名称
      enterpriseList: [],
      // 方向
      directionList: direction,
      // 城市
      provincesList: datas,
      // 地区
      cityList: {},
      // 试题标签
      tagsLists: [],
      // 多选框存储数据
      checkList: [],
      imageUrl: '',
      // 表单数据
      formData: {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [
          { isRight: 0, title: '', code: 'A:', imgUrl: '' },
          { isRight: 0, title: '', code: 'B:', imgUrl: '' },
          { isRight: 0, title: '', code: 'C:', imgUrl: '' },
          { isRight: 0, title: '', code: 'D:', imgUrl: '' }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: ''
      },
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'blur' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'blur' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'blur' }
        ],
        city: [
          { required: true, message: '请选择地区', trigger: 'blur' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'blur' }
        ],
        questionType: [
          { required: true, message: '请选择题型', trigger: 'change' }
        ],
        difficulty: [
          { required: true, message: '请选择难度', trigger: 'blur' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    // 学科
    this.getSubjectIDList()
    // 企业
    this.getEnterpriseIDList()
    this.getFormData()
  },
  watch: {
    // 监视城市变化
    'formData.province': function () {
      this.getArea()
    }
  },
  methods: {
    // 多选框添加按钮
    addCheckboxList () {
      const add = this.formData.options.length
      this.formData.options.push({ isRight: false, title: '', code: `${String.fromCharCode(65 + add)}:`, imgUrl: '' })
    },
    // 判断单选框
    changeIsRight (i) {
      this.formData.options.map(item => {
        item.isRight = 0
      })
      this.formData.options[i].isRight = 1
    },
    // img赋值
    addImg (i) {
      this.formData.options[i].imgUrl = this.imageUrl
    },
    // 选择本地电脑图片
    chooseImg (i) {
      // 说明：点击按钮触发
      this.$refs.uploadInput[i].click()
    },
    preview (e) {
      // 选择了图片进行预览
      // console.log('选择图片', e.target.files[0])
      /**
         * 使用FileReader构造函数
         */
      // 1. 实例化FileReader对象
      const fr = new FileReader()
      // 2. 使用fr.readAsDataURL 方法读取图片内容
      fr.readAsDataURL(e.target.files[0])
      // 3. 通过fr的onload事件获取 =》读取图片内容base64格式
      fr.onload = (event) => {
        this.imageUrl = event.target.result
      }
    },
    // 获取学科数据
    async getSubjectIDList () {
      try {
        const { data } = await subjectList(this.params)
        // console.log(data)
        this.subjectList = data.items
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 目录
    async getDirectorysList () {
      try {
        const { data } = await directorysApi(this.params)
        // console.log(data)
        this.directorysList = data.items
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 获取企业数据
    async getEnterpriseIDList () {
      try {
        const { data } = await list()
        // console.log(data)
        this.enterpriseList = data.items
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 初始化 获取目录、试题标签数据
    async changeSubject (id) {
      try {
        // 目录
        const res = await directorysApi({
          ...this.params,
          subjectID: id
        })
        // console.log(data)
        this.directorysList = res.data.items
        // 标签
        const res2 = await tagsList({
          ...this.params,
          subjectID: id
        })
        // console.log(data)
        this.tagsLists = res2.data.items
      } catch (error) {
        this.$message.error(error)
      }
    },
    // 城市联动
    getArea () {
      let citys = []
      this.provincesList.forEach(item => {
        // console.log(item.city)
        if (item.city === this.formData.province) {
          citys = item
        }
      })
      if (citys) {
        this.cityList = citys.area
      }
    },
    // 试题标签 格式转换
    tagsString () {
      if (this.formData.tags !== '') {
        this.formData.tags = this.formData.tags.toString()
      }
    },
    // 清空表单
    clearForm () {
      this.$refs.formData.resetFields()
      this.formData = {
        // 学科
        subjectID: '',
        // 目录
        catalogID: '',
        // 企业
        enterpriseID: '',
        // 城市
        province: '',
        // 地区
        city: '',
        // 方向
        direction: '',
        // 题型
        questionType: '1',
        // 难度
        difficulty: '1',
        // 题干
        question: '',
        // 选项
        options: [
          { isRight: 0, title: '', code: 'A:', imgUrl: '' },
          { isRight: 0, title: '', code: 'B:', imgUrl: '' },
          { isRight: 0, title: '', code: 'C:', imgUrl: '' },
          { isRight: 0, title: '', code: 'D:', imgUrl: '' }
        ],
        // 解析视频
        videoURL: '',
        // 答案解析
        answer: '',
        // 题目备注
        remarks: '',
        // 试题标签
        tags: ''
      }
    },
    // 添加\修改 试题
    submitForm () {
      this.tagsString()
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          if (this.formData.id) {
            await update(this.formData)
          } else {
            await add(this.formData)
          }
          this.$message.success(`${this.formData.id ? '添加' : '修改'}成功`)
          this.$router.push('/questions/list')
          // 清空表单
          this.clearForm()
        }
      })
    }
  }
}

</script>
<style lang="scss" scoped>
::v-deep .el-input__inner {
  width: 400px;
  height: 36px;
}
::v-deep .el-textarea__inner {
  width: 400px;
  height: 96px;
}
// 城市输入框
::v-deep .city {
  .el-input__inner {
    width: 198px;
    margin-right: 4px;
  }
}
// 选项单选
::v-deep .option_item {
  padding-bottom: 20px;
  display: flex;
  justify-content: start;
  align-items: center;
  .el-radio,
  .el-checkbox {
    margin-right: 10px;
    line-height: 14px;
  }
  .el-input__inner,
  .el-input--mini {
    width: 240px;
    height: 36px;
    margin-right: 5px;
  }
  .uploadImg {
    position: relative;
    width: 100px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    background-color: #fff;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    span {
      padding: 20px;
      font-size: 14px;
    }
    .el-icon-circle-close {
      position: absolute;
      top: -10px;
      right: -10px;
      font-size: 18px;
    }
  }
}
// 覆盖富文本编辑器样式
::v-deep .ql-editor {
  // 最小300，但是如果盒子内容超过300，会根据内容自适应（跟随内容变高）
  min-height: 200px;
}
// 修正行号问题
::v-deep .ql-toolbar.ql-snow .ql-formats {
  line-height: normal;
}
</style>
